<script setup lang="ts">
  import { getOrderListSelectField, workModulePageSelect } from '@/api/order'
  import { getNetworkPageSelect } from '@/api/network'
  import { computed, onMounted, ref } from 'vue'
  import { FilterForm } from './types'
  import DateRange from '@/components/DateRange.vue'
  import _ from 'lodash'
  import { useGetSourceOptionList } from '@/services/pages/order/useSoruce'
  import { RefreshRight } from '@element-plus/icons-vue'
  import { HMessageBox } from '@/components/common/message'

  const {
    optionList: sourceOptionList,
    getOptionListParam: getSourceOptionListParam,
    getOptionListLoading: getSourceOptionListLoading,
    getOptionList: getSourceOptionList,
  } = useGetSourceOptionList()

  const emits = defineEmits<{
    (e: 'getList'): void
    (e: 'clear'): void
  }>()

  /**
   * dateFieldType   - 时间字段类型：1-报单日期，2-完工日期，3-结算日期
   * dateType        - 时间类型：1-时间区间，2-今天，3-本周，4-本月，5-过去三个月
   * orderStartTime  - 报单开始时间
   * orderEndTime    - 报单结束时间
   * orderNo         - 工单单号
   * goodsSearch     - 设备搜索：品牌/产品名称/产品型号
   * orderUserSearch - 工单公司搜索关键词：客户名称/公司手机号/公司地址
   * fieldSearch     - 工单字段搜索关键词
   * fieldId         - 工单字段ID
   * moduleVal       - 工单类型
   * workSourceIds   - 工单来源
   */
  const filterForm = ref<FilterForm>({
    dateFieldType: 1,
    dateType: null,
    orderStartTime: null,
    orderEndTime: null,
    orderNo: null,
    goodsSearch: null,
    orderUserSearch: null,
    fieldSearch: null,
    fieldId: null,
    moduleVal: [],
    engineer: '',
    snCode: '',
    goodsCode: '',
    orderstatus: [],
    networkIds: [],
    workSourceIds: [],
  })
  const filterConditionClass = computed(() => {
    return {
      createTimeType: [1, 2].includes(filterForm.value.dateFieldType) ? 'has-filter-class' : '',
      selectTimeType: [1, 2, 3, 4, 5].includes(filterForm.value.dateType) ? 'has-filter-class' : '',
      orderType: filterForm.value.moduleVal.length > 0 ? 'has-filter-class' : '',
      orderStatus: filterForm.value.orderstatus.length > 0 ? 'has-filter-class' : '',
      network: {
        'network-select': true,
        'has-filter-class': filterForm.value.networkIds.length > 0,
      },
      source: filterForm.value.workSourceIds.length > 0 ? 'has-filter-class' : '',
      orderNo: filterForm.value.orderNo ? 'has-filter-class' : '',
      goodSearch: filterForm.value.goodsSearch ? 'has-filter-class' : '',
      goodCode: filterForm.value.goodsCode ? 'has-filter-class' : '',
      userSearch: filterForm.value.orderUserSearch ? 'has-filter-class' : '',
      engineer: filterForm.value.engineer ? 'has-filter-class' : '',
      keyword: filterForm.value.fieldSearch ? 'has-filter-class' : '',
      snCode: filterForm.value.snCode ? 'has-filter-class' : '',
    }
  })
  const inputFilterConditionList = ref<
    | 'orderNo'
    | 'goodSearch'
    | 'goodCode'
    | 'snCode'
    | 'userSearch'
    | 'engineer'
    | 'customFieldSearch'
  >('orderNo')
  const firstSelectFilterCondition = ref<{
    value: 'orderType' | 'orderStatus' | 'network' | 'source'
    label: 'first' | 'second'
  }>({
    value: 'orderType',
    label: 'first',
  })
  const secondSelectFilterCondition = ref<{
    value: 'orderType' | 'orderStatus' | 'network' | 'source'
    label: 'first' | 'second'
  }>({
    value: 'orderStatus',
    label: 'second',
  })
  const selectFilterConditionOptions = [
    { value: 'orderType', label: '工单类型' },
    { value: 'orderStatus', label: '工单状态' },
    { value: 'network', label: '部门' },
    { value: 'source', label: '工单来源' },
  ]

  // 工单状态
  const orderstatusList = ref([
    { title: '待派单', value: 1 },
    { title: '待部门确认', value: 2 },
    { title: '处理中', value: 3 },
    { title: '已完成', value: 4 },
    { title: '已取消', value: 5 },
  ])
  const modules = ref(null)
  // 日期范围组件实例
  const dateRangeRef = ref<InstanceType<typeof DateRange> | null>(null)

  // 开始日期是否大于结束日期
  const isStartDateGreaterThanEndDate = ref(false)

  // 时间类型选项
  const dateTypeOptional = ref([
    { title: '今天', value: 2 },
    { title: '本周', value: 3 },
    { title: '本月', value: 4 },
    { title: '自定义时间', value: 1 },
  ])

  // 自定义字段选项
  const customFiledOptional = ref<Array<{ id: string; name: string; select: boolean }>>([])

  // 获取自定义字段下拉
  const getOptions = async () => {
    const res = await getOrderListSelectField()
    customFiledOptional.value = res.data.data.rows
  }

  // 获取筛选
  const getFilter = () => {
    if (isStartDateGreaterThanEndDate.value) {
      HMessageBox.error('开始日期不能大于结束日期')
      return null
    }
    return { ...filterForm.value }
  }
  // 工单类型下拉数据
  const getworkModulePageSelect = async (val) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }

    const res = await workModulePageSelect(data)
    modules.value = []
    if (res.data.success) {
      modules.value = res.data.data.rows
    }
  }
  const networkSelectData = ref([])
  const net_name = ref('')
  const net_total = ref(0)

  // 获取部门下拉选项加载
  const getNetworkOptionsLoading = ref(false)

  /**
   * 获取部门下拉选项
   * @param name - 搜索关键字
   */
  const getNetworkOptions = async () => {
    networkSelectData.value = []
    getNetworkOptionsLoading.value = true
    const res = await getNetworkPageSelect({
      name: net_name.value,
      page: 0,
      limit: 0,
    })
    getNetworkOptionsLoading.value = false
    net_total.value = Number(res.data.data.total)
    networkSelectData.value = res.data.data.rows
  }

  // 重置事件
  const reset = () => {
    if (dateRangeRef.value) {
      dateRangeRef.value.resetDateRange()
    }
    isStartDateGreaterThanEndDate.value = false
    Object.assign(filterForm.value, {
      dateFieldType: 1,
      dateType: null,
      orderStartTime: null,
      orderEndTime: null,
      orderNo: null,
      goodsSearch: null,
      orderUserSearch: null,
      fieldSearch: null,
      fieldId: null,
      moduleVal: [],
      source: [],
      engineer: '',
      snCode: '',
      goodsCode: '',
      orderstatus: [],
      networkIds: [],
      workSourceIds: [],
    })
  }

  // 日期更新事件
  const handleDateChange = (param: {
    startDate: string
    endDate: string
    isStartDateGreaterThanEndDate: boolean
  }) => {
    filterForm.value.orderStartTime = param.startDate
    filterForm.value.orderEndTime = param.endDate
    isStartDateGreaterThanEndDate.value = param.isStartDateGreaterThanEndDate
    if (param.isStartDateGreaterThanEndDate) {
      HMessageBox.error('开始日期不能大于结束日期')
      return
    }
    emits('getList')
  }

  /**
   * 报单时间类型更新
   */
  const onDateTypeChange = () => {
    if ([2, 3, 4].includes(filterForm.value.dateType)) {
      emits('getList')
    }
  }

  /**
   * 重置事件
   */
  const onReset = () => {
    filterForm.value = {
      dateFieldType: 1,
      dateType: null,
      orderStartTime: null,
      orderEndTime: null,
      orderNo: null,
      goodsSearch: null,
      orderUserSearch: null,
      fieldSearch: null,
      fieldId: null,
      moduleVal: [],
      engineer: '',
      snCode: '',
      goodsCode: '',
      orderstatus: [],
      networkIds: [],
      workSourceIds: [],
    }
    inputFilterConditionList.value = 'orderNo'
    firstSelectFilterCondition.value = {
      value: 'orderType',
      label: 'first',
    }
    secondSelectFilterCondition.value = {
      value: 'orderStatus',
      label: 'second',
    }
    emits('getList')
    emits('clear')
  }

  /**
   * 获取部门下拉选项
   */
  const handleGetNetworkOptions = _.debounce((keyword: string) => {
    if (keyword !== net_name.value) {
      net_name.value = keyword
      getNetworkOptions()
    }
  }, 600)

  /**
   * 工单来源筛选事件
   * @param {string} keyword - 搜索关键字
   */
  const handleSourceFilter = _.debounce((keyword: string) => {
    if (getSourceOptionListParam.value.name !== keyword) {
      getSourceOptionListParam.value.name = keyword
      getSourceOptionList()
    }
  }, 600)

  onMounted(() => {
    getOptions()
    getworkModulePageSelect('')
    getNetworkOptions()
  })

  defineExpose({
    getFilter,
    reset,
    setDateType: (type: 'today' | 'week' | 'month') => {
      switch (type) {
        case 'today':
          filterForm.value.dateType = 2
          break
        case 'week':
          filterForm.value.dateType = 3
          break
        case 'month':
          filterForm.value.dateType = 4
          break
      }
    },
    getSourceOptionList,
  })
</script>

<template>
  <div class="filter">
    <!-- 时间字段类型 -->
    <el-select
      v-model="filterForm.dateFieldType"
      placeholder="下单日期"
      style="width: 100px"
      :class="filterConditionClass.createTimeType"
    >
      <el-option label="报单日期" :value="1" />
      <el-option label="完工日期" :value="2" />
      <!-- <el-option label="结算日期" :value="3" /> -->
    </el-select>

    <!--选择时间-->
    <el-select
      v-model="filterForm.dateType"
      placeholder="选择时间"
      style="width: 110px"
      clearable
      :class="filterConditionClass.selectTimeType"
      @change="onDateTypeChange"
      @clear="emits('getList')"
    >
      <el-option
        v-for="item in dateTypeOptional"
        :key="item.value"
        :value="item.value"
        :label="item.title"
      />
    </el-select>

    <!--日期范围-->
    <DateRange
      v-if="filterForm.dateType === 1"
      ref="dateRangeRef"
      class="date_range"
      @change="handleDateChange"
    />

    <template
      v-for="(item, index) in [firstSelectFilterCondition, secondSelectFilterCondition]"
      :key="index"
    >
      <el-select v-model="item.value" placeholder="请选择查询条件" style="width: 100px">
        <el-option
          v-for="(option, optionIndex) in selectFilterConditionOptions"
          :key="optionIndex"
          :value="option.value"
          :disabled="
            item.label === 'first'
              ? secondSelectFilterCondition.value === option.value
              : firstSelectFilterCondition.value === option.value
          "
          :label="option.label"
        />
      </el-select>

      <!-- 工单类型 -->
      <el-select
        v-if="item.value === 'orderType'"
        v-model="filterForm.moduleVal"
        multiple
        collapse-tags
        collapse-tags-tooltip
        placeholder="请选择工单类型"
        style="width: 190px"
        :class="filterConditionClass.orderType"
        @change="emits('getList')"
        @clear="emits('getList')"
      >
        <el-option v-for="item in modules" :key="item.id" :value="item.id" :label="item.name" />
      </el-select>

      <!-- 工单状态 -->
      <el-select
        v-if="item.value === 'orderStatus'"
        v-model="filterForm.orderstatus"
        multiple
        collapse-tags
        collapse-tags-tooltip
        placeholder="请选择工单状态"
        style="width: 190px"
        :class="filterConditionClass.orderStatus"
        @change="emits('getList')"
        @clear="emits('getList')"
      >
        <el-option
          v-for="item in orderstatusList"
          :key="item.value"
          :value="item.value"
          :label="item.title"
        />
      </el-select>

      <!-- 工单部门 -->
      <el-select
        v-if="item.value === 'network'"
        v-model="filterForm.networkIds"
        multiple
        collapse-tags
        collapse-tags-tooltip
        placeholder="请选择部门"
        style="width: 190px"
        filterable
        :filter-method="handleGetNetworkOptions"
        :loading="getNetworkOptionsLoading"
        :class="filterConditionClass.network"
        @change="emits('getList')"
        @clear="emits('getList')"
      >
        <el-option
          v-for="item in networkSelectData"
          :key="item.id"
          :value="item.id"
          :label="item.name"
        >
          <div style="display: flex; column-gap: 5px; padding-right: 32px">
            <h-tooltip-text :text="item.name" :max-width="160" :height="32"></h-tooltip-text>
            <span style="color: #999; font-size: 12px">
              {{ item.code }}
            </span>
          </div>
        </el-option>
      </el-select>

      <!-- 工单来源 -->
      <el-select
        v-if="item.value === 'source'"
        v-model="filterForm.workSourceIds"
        multiple
        collapse-tags
        collapse-tags-tooltip
        placeholder="请选择工单来源"
        style="width: 190px"
        :loading="getSourceOptionListLoading"
        filterable
        :filter-method="handleSourceFilter"
        :class="filterConditionClass.source"
        @change="emits('getList')"
        @clear="emits('getList')"
      >
        <el-option
          v-for="item in sourceOptionList.filter((item) => !item.disabled)"
          :key="item.id"
          :value="item.id"
          :label="item.name"
          :disabled="item.disabled"
        />
      </el-select>
    </template>

    <el-select v-model="inputFilterConditionList" placeholder="请选择查询条件" style="width: 190px">
      <el-option value="orderNo" label="工单编号" />
      <el-option value="goodSearch" label="设备名称/型号" />
      <el-option value="goodCode" label="设备编号" />
      <el-option value="snCode" label="序列号" />
      <el-option value="userSearch" label="所属公司/送修公司/送修人" />
      <el-option value="engineer" label="工程师名称/手机号" />
      <el-option value="customFieldSearch" label="自助查询" />
    </el-select>

    <!--工单编号-->
    <el-input
      v-if="inputFilterConditionList.includes('orderNo')"
      v-model.trim="filterForm.orderNo"
      style="width: 190px"
      clearable
      placeholder="请输入关键字"
      :class="filterConditionClass.orderNo"
      @keyup.enter="emits('getList')"
      @clear="emits('getList')"
    />

    <!--设备名称/型号-->
    <el-input
      v-if="inputFilterConditionList.includes('goodSearch')"
      v-model.trim="filterForm.goodsSearch"
      clearable
      placeholder="请输入关键字"
      style="width: 190px"
      :class="filterConditionClass.goodSearch"
      @keyup.enter="emits('getList')"
      @clear="emits('getList')"
    />

    <!-- 设备编号 -->
    <el-input
      v-if="inputFilterConditionList.includes('goodCode')"
      v-model.trim="filterForm.goodsCode"
      clearable
      placeholder="请输入关键字"
      style="width: 190px"
      :class="filterConditionClass.goodCode"
      @keyup.enter="emits('getList')"
      @clear="emits('getList')"
    />

    <!-- 序列号 -->
    <el-input
      v-if="inputFilterConditionList.includes('snCode')"
      v-model.trim="filterForm.snCode"
      clearable
      placeholder="请输入关键字"
      style="width: 190px"
      :class="filterConditionClass.snCode"
      @keyup.enter="emits('getList')"
      @clear="emits('getList')"
    />

    <!--搜索客户名称/手机号/地址-->
    <el-input
      v-if="inputFilterConditionList.includes('userSearch')"
      v-model.trim="filterForm.orderUserSearch"
      clearable
      placeholder="请输入关键字"
      style="width: 190px"
      :class="filterConditionClass.userSearch"
      @keyup.enter="emits('getList')"
      @clear="emits('getList')"
    />

    <!--搜索工程师名称/手机号-->
    <el-input
      v-if="inputFilterConditionList.includes('engineer')"
      v-model.trim="filterForm.engineer"
      clearable
      placeholder="请输入关键字"
      style="width: 190px"
      :class="filterConditionClass.engineer"
      @keyup.enter="emits('getList')"
      @clear="emits('getList')"
    />

    <!--关键字-->
    <el-input
      v-if="inputFilterConditionList.includes('customFieldSearch')"
      v-model.trim="filterForm.fieldSearch"
      clearable
      placeholder="请输入关键字"
      style="width: 190px"
      :class="filterConditionClass.keyword"
      @keyup.enter="emits('getList')"
      @clear="emits('getList')"
    >
      <template #prepend>
        <el-select
          v-model="filterForm.fieldId"
          clearable
          class="item-select"
          placeholder="自助查询"
          style="width: 110px"
          @clear="emits('getList')"
        >
          <el-option
            v-for="item in customFiledOptional"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </template>
    </el-input>

    <HButton type="primary" @click="emits('getList')">
      <el-icon>
        <Search />
      </el-icon>
      搜索
    </HButton>

    <HButton @click="onReset">
      <el-icon>
        <RefreshRight />
      </el-icon>
      重置
    </HButton>
  </div>
</template>

<style scoped lang="scss">
  .filter {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    justify-content: flex-start;
  }

  .network-select {
    width: 220px;

    :deep(.el-tag) {
      max-width: 80px !important;
    }
  }

  .has-filter-class {
    :deep(.el-select__wrapper) {
      box-shadow: 0 0 0 1px #007cff inset;

      .el-select__placeholder {
        color: #007cff;
      }

      .el-tag.el-tag--info {
        --el-tag-bg-color: #f2fbff;
        --el-tag-text-color: #007cff;
        --el-tag-hover-color: #007cff;
      }
    }

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #007cff inset;

      .el-input__inner {
        color: #007cff;
      }
    }
  }
</style>
